package spring.security.core.util;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Map;
import net.sf.cglib.beans.BeanMap;

@SuppressWarnings({"rawtypes", "unchecked"})
public class MapUtils extends org.apache.commons.collections.MapUtils {
	
	public static <T> T toBean(Map<String, Object> map, T bean) {
		if (map != null && bean != null) {
			BeanMap beanMap = BeanMap.create(bean);
			beanMap.putAll(map);
			return bean;
		} else {
			return null;
		}
	}

	public static Map<String, String> getUrlParams(String param) {
		HashMap map = Maps.newHashMap();
		if (Strings.isNullOrEmpty(param)) {
			return map;
		} else {
			String[] params = param.split("&");

			for (int i = 0; i < params.length; ++i) {
				String[] p = params[i].split("=");
				if (p.length == 2) {
					map.put(p[0], p[1]);
				}
			}

			return map;
		}
	}

	public static String getUrlParamsByMap(String url, Map<String, Object> param) {
		return getUrlParamsByMap(url, param, false);
	}

	public static String getUrlParamsByMap(String url, Map<String, Object> param, boolean nullToStr) {
		if (param != null && !param.isEmpty()) {
			StringBuilder builder = new StringBuilder();
			builder.append(url);
			if (url.indexOf("?") == -1) {
				builder.append("?");
			}

			param.forEach((k, v) -> {
				if (nullToStr) {
					if (v != null) {
						builder.append(k + "=" + v).append("&");
					}
				} else {
					builder.append(k + "=" + v).append("&");
				}

			});
			return builder.substring(0, builder.length() - 1);
		} else {
			return url;
		}
	}
	
}
